import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

void main() {
  runApp(const MaterialApp(home: HomePage()));
}

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List<Widget> list = [];
  // key
  GlobalKey key1 = GlobalKey();
  // GlobalKey key2 = GlobalKey();
  // GlobalKey key3 = GlobalKey();
  @override
  void initState() {
    super.initState();
    list = [
      Box(
        key: UniqueKey(),
        color: Colors.teal,
      ),
      Box(
        key: const ValueKey('1'),
        color: Colors.orange,
      ),
      Box(
        key: const ObjectKey({}),
        color: Colors.red,
      ),
      Box(
        key: key1,
        color: Colors.yellow,
      ),
    ];
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('你好flutter1'),
        ),
        body: Center(
          child: Column(
            children: list,
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            var boxState = key1.currentState as _BoxState;
            setState(() {
              // 打乱list
              list.shuffle();
              // FIXME 值改变了，但是页面没响应
              boxState._couter++;
            });
          },
          child: const Icon(Icons.add),
        ),
      ),
    );
  }
}

class Box extends StatefulWidget {
  var key;
  Color color;
  Box({this.key, this.color = Colors.orange});

  @override
  State<Box> createState() => _BoxState();
}

class _BoxState extends State<Box> {
  int _couter = 0;
  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: 100,
      height: 100,
      child: ElevatedButton(
        style: ButtonStyle(
          backgroundColor: MaterialStateProperty.all(widget.color),
        ),
        onPressed: () {
          setState(() {
            _couter++;
          });
        },
        child: Text(
          '${_couter}',
          style: TextStyle(color: Colors.white, fontSize: 30),
        ),
      ),
    );
  }
}
